import React, {useEffect, useState} from 'react';
import {Form, message, Modal} from 'antd';
import {http} from 'libs';
import store from './store';
import {TableCard} from "components";

export default function IForm() {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [records, setRecords] = useState([]);

  const columns = [
    {
      title: 'No.',
      width: 50,
      render: (_, __, index) => <span className="idx">{index + 1}</span>
    },
    {title: '变动前成本价', dataIndex: 'old_price'},
    {title: '变动后成本价', dataIndex: 'new_price'},
    {title: '操作人员', dataIndex: 'created_by_name'},
    {title: '变动类型', dataIndex: 'rel_type_alias'},
    {title: '变动时间', dataIndex: 'created_at'},
  ]

  useEffect(() => {
    if (store.record.id) {
      setPage(1)
      getData()
    }
  }, [store.record]);

  function getData() {
    setLoading(true)
    let data = {product_id: store.record.id, page: page, page_size: pageSize}
    http.get('/api/product/log/', {params: data})
      .then(res => {
        setRecords(res)
        setPage(page + 1)
      })
      .finally(() => setLoading(false))
  }

  function handleSubmit() {
    setLoading(true);
    const formData = form.getFieldsValue();
    formData['id'] = store.record.id;
    http.patch('/api/user/', formData)
      .then(() => {
        message.success('操作成功');
        store.set('pwdFormVisible', false);
        store.fetchRecords()
      })
      .finally(() => setLoading(false))
  }

  return (
    <Modal
      open
      width={800}
      maskClosable={false}
      title={`[${store.record.name}] 成本价变动记录`}
      onCancel={store.vSet('logVisible', false)}
      onOk={store.vSet('logVisible', false)}
      okText="关闭"
      cancelButtonProps={{style: {display: 'none'}}}
    >
      <TableCard
        rowKey="id"
        loading={loading}
        dataSource={records}
        columns={columns}
        pagination={{
          showSizeChanger: true,
          showLessItems: true,
          hideOnSinglePage: true,
          pageSizeOptions: ['10', '20', '50', '100'],
          onChange: (page, pageSize) => {
            setPage(page)
            setPageSize(pageSize)
            getData()
          }
        }}
      />
    </Modal>
  )
}